<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\User;
use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 会议类型管理
 *
 * @icon fa fa-circle-o
 */
class Meettype extends Backend
{
    protected $relationSearch = true;

    /**
     * Meettype模型对象
     * @var \app\admin\model\Meettype
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Meettype;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("signTypeList", ['0'=>'无需签到','1'=>'页面签到','2'=>'二维码签到']);
        $this->view->assign("meetTypeList", ['0'=>'清外会议系统','1'=>'听评课系统']);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with([
                'collector'
            ])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $k => $v) {
            if(!empty($v['faqi_ids'])){
                $userids = explode(',',$v['faqi_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->faqi_ids = implode(',',$a1);
            }
            if(!empty($v['attend_meet_ids'])){
                $userids = explode(',',$v['attend_meet_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->attend_meet_ids = implode(',',$a1);
            }
            if(!empty($v['attend_topic_ids'])){
                $userids = explode(',',$v['attend_topic_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->attend_topic_ids = implode(',',$a1);
            }
            if(!empty($v['approver_ids'])){
                $userids = explode(',',$v['approver_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->approver_ids = implode(',',$a1);
            }
            if(!empty($v['issued_ids'])){
                $userids = explode(',',$v['issued_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->issued_ids = implode(',',$a1);
            }
            if(!empty($v['check_ids'])){
                $userids = explode(',',$v['check_ids']);
                $a1 = User::where('id','in',$userids)->column('nickname');
                $v->check_ids = implode(',',$a1);
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
//        if($params['meet_type'] == 1 && $params['type'] != 5){
//            $this->error('清外活动系统，只能选其他会议');
//        }
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
//        if($params['meet_type'] == 1 && $params['type'] != 5){
//            $this->error('清外活动系统，只能选其他会议');
//        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
           /* $auser = User::get($params['approver_ids']);
            if($auser){
                $auser->is_check_room = 1;
                $auser->save();
            }*/
            $auser = User::get($params['issued_ids']);
            if($auser){
                $auser->is_issued = 1;
                $auser->save();
            }
            $auser = User::get($params['check_ids']);
            if($auser){
                $auser->is_leader = 1;
                $auser->save();
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
